import router from 'koa-router';
import TileUtil4326 from '../lib/TileTool/TileUtil4326';
import TileUtil3857 from '../lib/TileTool/TileUtil3857';
import getFilePathList from '../lib/FSTool/getFilePathList';
import configTool from '../com/configTool';

const TileRoutes = new router({prefix: '/TileServer'});


const tileUtil3857 = new TileUtil3857();
const tileUtil4326 = new TileUtil4326();

// 通配符的写法
TileRoutes
	.all('/getTilesByGeoJson', async (ctx: any) => {
		ctx.set('content-type', 'application/json;charset=utf-8');
		const {
			token,
			tileSchema,
			level,
			dataSourceName,
			dataSourceToken,
			targetDirectory,
			geoJson
		} = ctx.request.body;

		const tileUtil = tileSchema === 'layer-xyz-3857' ? tileUtil3857 : tileUtil4326;

		const tileList = tileUtil.getTilesByGeoJson(geoJson, level);


		ctx.body = JSON.stringify({
			code: 200,
			message: '瓦片分析成功',
			data: tileList
		});
		ctx.status = 200;
	})
	.get('/getTileSetList', async (ctx: any) => {
		ctx.set('content-type', 'application/json;charset=utf-8');

		let fileList =  getFilePathList(configTool.wwwPath) || [];

		fileList = fileList.filter((item: string) => {
			return item.indexOf('tileset.json') > -1;
		});

		fileList = fileList.sort();

		ctx.body = fileList.map((item: string) => {
			const url = item.replace(configTool.wwwPath, '').replaceAll('\\', '/');
			const md5 = require('crypto').createHash('md5').update(item).digest('hex');
			return {
				pid: md5,
				name: item.split('\\')[item.split('\\').length - 2],
				url: url,
				diskPath: item
			};
		}).filter((item: any) => {
			// 判断 url 里只有两个 ‘/’ 号
			return  item.url.split('/').length === 3;
		});
	});


export default TileRoutes;
